//
//  QFNewFeatureViewController.swift
//  sinaWeibo
//
//  Created by apple on 16/3/1.
//  Copyright © 2016年 Qifeng Yan. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"

private let itemCount = 4

class QFNewFeatureViewController: UICollectionViewController {

    // MARK: - 属性
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    

    
    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(QFNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        layout.itemSize = UIScreen.mainScreen().bounds.size // 设置item大小（cell 的大小）
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal // 设置水平滚动
        layout.minimumLineSpacing = 0   // 设置列间距
        layout.minimumInteritemSpacing = 0  // 设置行间距
        
        collectionView?.pagingEnabled = true  // 设置分页效果
        collectionView?.bounces = false     // 取消弹簧效果
        
    }
    
}

extension QFNewFeatureViewController {
    
    // MARK: - 数据源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! QFNewFeatureCell
        
        cell.itemIndex = indexPath.item
        
        return cell
    }
    
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        let index = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        if index == itemCount - 1 {
            // 获取cell
            let indexPath = NSIndexPath(forItem: index, inSection: 0)
            if let cell = collectionView?.cellForItemAtIndexPath(indexPath) as? QFNewFeatureCell {
                // 调用动画
                cell.startButtonAnimation()
            }
            
        }
    }
    
}

//  - 自定义cell
class QFNewFeatureCell: UICollectionViewCell {
    
    
    // MARK: - 属性
    
    var itemIndex: Int = 0 {
        didSet {
            bkgImageView.image = UIImage(named: "new_feature_\(itemIndex+1)")
            startButton.hidden = true
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 加载UI
    private func prepareUI() {
        
        // 添加到父控件
        contentView.addSubview(bkgImageView)
        contentView.addSubview(startButton)
        
        // 添加背景约束
        bkgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        
        // 添加按钮约束
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-160)
        }
    }
    
    // MARK: - 按钮的动画效果
    private func startButtonAnimation() {
        // 显示按钮
        startButton.hidden = false
        
        // 设置按钮的缩放比例
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        // 实现弹簧动画
        /**
        UIView 弹簧动画
        - parameter <Tduration:             动画持续时间 一般 1秒
        - parameter delay:                  动画的延迟时间 0.1
        - parameter usingSpringWithDamping: 弹簧效果 系数0-1 一般设置0.5
        - parameter initialSpringVelocity:  弹簧效果的初始化速度 一般 5
        - parameter options:                选项 一帮这个为0 在swift中是(rawValue: 0)
        - parameter animations:             要执行的动画效果
        - parameter completion:             动画结束后 做的事情
        */
        UIView.animateWithDuration(1, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            // 还原默认的transform
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
//                print("动画完成")
        }
    }
    
    
    /// 懒加载
    private lazy var bkgImageView: UIImageView = UIImageView()
    
    /// 懒加载 开始体验按钮
    private lazy var startButton:UIButton = {
        let button = UIButton()
        
        // 设置
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.sizeToFit()
        button.addTarget(self, action: "startButtonDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    // MARK: - 监听 体验按钮的点击事件
    func startButtonDidClick() {
        // 拿到APPDelegate
//        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//        appDelegate.switchRootViewController(true)
        AppDelegate.outSwitchRootViewController(true)
    }
    
}
